#include <GL/glut.h>
#include <math.h>

#define PI 3.1415f
GLuint dl_sky;

GLuint tex_sky;

GLuint loadBitmap(char *path);


void doSkyPoint(float aR, float aH)
{
	float r = cos(aH);
	float h = sin(aH);

	glVertex3f(r * sin(aR), h, r*cos(aR));
}

// stepsR - segments on the circunference
// stepsH - segmenth on height
// texRepeat - how often the texture repeats
void drawSky(int stepsR, int stepsH, int texRepeat)
{
	float stepR = 1.0f / stepsR;
	float stepH = 1.0f / stepsH;

	glColor3f(1.0f, 1.0f, 1.0f);

	float angleR = 0;
	float angleH = 0;
	for (angleH = 0;angleH<=.5+stepH/5;angleH+=stepH)
	{
		glBegin(GL_TRIANGLE_STRIP);
		for (angleR=0;angleR<=1.0+stepR/5;angleR+=stepR)
		{
			glTexCoord2f(angleR, angleH+stepH);
			doSkyPoint(angleR * 2 * PI, (angleH+stepH)*PI);
			glTexCoord2f(angleR, angleH);
			doSkyPoint(angleR * 2*PI, angleH * PI);
		}
		glEnd();
	}
}

void drawSnowMan() 
{
	glPushMatrix();
	glColor3f(1.0f, 1.0f, 1.0f);

	// Draw Body	
	glTranslatef(0.0f ,0.75f, 0.0f);
	glutSolidSphere(0.75f,20,20);


	// Draw Head
	glTranslatef(0.0f, 1.0f, 0.0f);
	glutSolidSphere(0.25f,20,20);

	// Draw Eyes
	glPushMatrix();
	glColor3f(0.0f,0.0f,0.0f);
	glTranslatef(0.05f, 0.10f, 0.18f);
	glutSolidSphere(0.05f,10,10);
	glTranslatef(-0.1f, 0.0f, 0.0f);
	glutSolidSphere(0.05f,10,10);
	glPopMatrix();

	// Draw Nose
	glColor3f(1.0f, 0.5f , 0.5f);
	glRotatef(0.0f,1.0f, 0.0f, 0.0f);
	glutSolidCone(0.08f,0.5f,10,2);

	glPopMatrix();
}

void initStuff()
{
	tex_sky = loadBitmap("data/texture/clouds.bmp");
}

void drawObjects()
{
	glDisable(GL_TEXTURE_2D);
	drawSnowMan();
	glEnable(GL_TEXTURE_2D);

	glPushMatrix();
	glScalef(50,50,50);
	glCullFace(GL_FRONT);
	drawSky(32,10,1);
	glCullFace(GL_BACK);
	glPopMatrix();
}

void drawMirror()
{
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	
	glBegin(GL_QUADS);
	glColor4f(1,1,1,0.5);
	glVertex3f(-5,0,-5);
	glVertex3f(-5,0,5);
	glVertex3f(5,0,5);
	glVertex3f(5,0,-5);
	glEnd();
	glDisable(GL_BLEND);

}
void drawScene() 
{
	glClearStencil(0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

	glDisable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);
	glEnable (GL_STENCIL_TEST); 
	glStencilFunc (GL_ALWAYS, 1,1); 
	glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);	

	drawMirror();
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);

	glStencilFunc(GL_EQUAL, 1, 1);
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
	glPushMatrix();
	glScalef(1,-1,1);
	drawObjects();
	glPopMatrix();

	glDisable(GL_STENCIL_TEST);

	glEnable(GL_BLEND);
	drawMirror();
	drawObjects();
}
void setOption(char c)
{
}
